package com.douxg.learning.db.mybatis.plus.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class MetaObjectHandlerConfig implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        insetFileByKey("createTime", now, metaObject);
        insetFileByKey("updateTime", now, metaObject);
        insetFileByKey("status", 1, metaObject);
        setInsertFieldValByName("logicDelete", false, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        setUpdateFieldValByName("updateTime", now, metaObject);
    }

    public void insetFileByKey(String key, Object value, MetaObject metaObject) {
        try {
            if (metaObject.getValue(key) == null) {
                setInsertFieldValByName(key, value, metaObject);
            }
        } catch (Exception e) {

        }
    }
}
